import { Component, Input, OnInit } from '@angular/core';
import { SFSchema,SFSliderWidgetSchema,SFUploadWidgetSchema } from '@delon/form';
import { ApiService } from '@core/services/api';
import { HttpClient } from '@angular/common/http';
import { NzMessageService, NzModalRef, UploadFile } from 'ng-zorro-antd';
import { FormBuilder, FormGroup } from '@angular/forms';
import { format } from 'date-fns'

function getBase64(file: File): Promise<string | ArrayBuffer | null> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

@Component({
  selector: 'ad-edit',
  templateUrl: './ad-edit.component.html',
  styles: []
})
export class AdEditComponent implements OnInit {
  @Input()type: 0 | 1;
  @Input()
  set _param(value) {
    if (!value) return;
    this.param = value;
    this.getDeviceInfo(value.id).then(res => {
      console.log(res);
      this.param = res.data.deviceHostRke;
      
      if(this.param.deviceImages) {
        this.previewImage = this.param.deviceImages;
        this.fileList = [...[{
          id: '-1',
          status: 'done',
          url: this.previewImage
        }]]
      }
    })

  };
  validateForm!: FormGroup;
  fileList: any[] = [

  ];
  uploadUrl = '/network/minIo/uploadFile'
  previewVisible = false;
  previewImage: string | undefined = '';
  param: any;
  showForm = false;
  schema: SFSchema = {
    properties: {
      deviceId: {
        type: 'string',
        ui:{
          hidden:true
        }
      },
      title: {
        type: 'string',
        title: '标题',
        ui:{
          grid: {span: 24}
        }
      },
      type: {
        type: 'number',
        title: '类别',
        default:1,
        enum: [
          {label: '文字', value: 1},
          {label: '图片', value: 2},
          {label: '视频', value: 3}
        ],
        ui: {
          widget: 'select',
          grid: {span :24}
        }
      },
      inputText: {
        type:'string',
        title:'文本',
        ui:{
          widget:'textarea',
          autosize: { minRows: 4, maxRows: 6 },
          visibleIf:{
            type: val => val == 1
          }
        }
      },
      file: {
        type: 'string',
        title: '文件',
        enum: [
          {
            uid: -1,
            name: 'xxx.png',
            status: 'done',
            url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
            response: {
              resource_id: 1,
            },
          },
        ],
        ui: {
          widget: 'upload',
          action: '/network/minIo/uploadFile',
          resReName: 'resource_id',
          urlReName: 'url',
          // visibleIf:{
          //   type: val => val != 1
          // }
        } as SFUploadWidgetSchema,
      },
      beginDate: {
        type:'string',
        title:'开始时间',
        format: 'date-time',
        ui: {
          grid: {span: 12}
        }
      },
      endDate: {
        type:'string',
        title:'结束时间',
        format: 'date-time',
        ui: {
          grid: {span: 12}
        }
      },
      desc: {
        type:'string',
        title:'描述',
        ui:{
          widget:'textarea',
          autosize: { minRows: 4, maxRows: 6 },
        }
      }

    },
    "ui": {
      "spanLabelFixed": 150,
      "grid": {
        "span": 24
      }
    },
    required: ['deviceCode']
  }

  handlePreview = async (file: UploadFile) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj!);
    }
    this.previewImage = file.url || file.preview;
    this.previewVisible = true;
  };

  formSubmit(data) {
    this.msg.success('操作成功');
    this.modalRef.destroy('ok');
    //   const body: any = data;
    
    //   if (this.fileList.length> 0 && (this.fileList[0].response.status == '200' || this.fileList[0].url)) {
    //     data['deviceImages'] =this.fileList[0].url ||  this.fileList[0].response.data;
    //   }

    // const url = this.type === 0 ? '/core/host' : '/core/host/batch';
    // const method = this.type === 0 ? 'POST' : 'PUT';
    // this.http.request<any>(method, url,  { body}).subscribe(res => {
    //   console.log(res)
    //   if (res.status === '200') {
    //     this.msg.success('操作成功');
    //     this.modalRef.destroy('ok');
    //   } else {
    //     this.msg.error(res.message)
    //   }
    // })

  }

  getDeviceInfo(deviceId: string): Promise<any>{
    let body = {id:deviceId};
    return this.http.request<any>('POST', '/core/host/details',{body}).toPromise();
  }

  constructor(
    private api: ApiService,
    private http: HttpClient,
    private msg: NzMessageService,
    private modalRef: NzModalRef,
    private fb:FormBuilder
  ) { }

  async ngOnInit() {
    this.showForm = true;
    this.validateForm = this.fb.group({
      btime:new Date(),
      etime:new Date(),
      cbtime:new Date(),
      cetime:new Date(),
      lbtime:new Date(),
      letime:new Date(),
      // rangePickerTime: [[new Date(this.param.cardUsingStartTime),new Date(this.param.cardUsingEndTime)]]
    });
  }

}
